package com.ashlikun.zxing.analyze

import android.graphics.Rect
import com.ashlikun.zxing.DecodeConfig
import com.ashlikun.zxing.DecodeFormatManager
import com.ashlikun.zxing.analyze.ResultAnalyzer.DataAnalyzer
import com.ashlikun.zxing.analyze.ResultAnalyzer.DataAnalyzerResult
import com.ashlikun.zxing.gray.Dispatch
import com.ashlikun.zxing.gray.GrayScaleDispatch
import com.ashlikun.zxing.util.ScanUtils.hasDepencidesScale
import com.google.zxing.DecodeHintType
import com.google.zxing.Result

/**
 * 矩阵区域分析器：主要用于锁定具体的识别区域
 */
abstract class AreaRectAnalyzer(var mDecodeConfig: DecodeConfig) : DataAnalyzer {
    var mHints: Map<DecodeHintType, *>? = null

    val isMultiDecode
        get() = mDecodeConfig.isMultiDecode

    override val isMultipleCode
        get() = mDecodeConfig.isMultipleCode

    private val mAreaRectRatio
        get() = mDecodeConfig.areaRectRatio

    //灰度处理
    private var processDispatch: Dispatch? = null

    init {
        mHints = mDecodeConfig.hints
        if (hasDepencidesScale()) {
            processDispatch = GrayScaleDispatch
        }
    }

    override fun analyze(data: ByteArray?, width: Int, height: Int): DataAnalyzerResult? {
        val rect = mDecodeConfig.calculateScanningArea(width, height)
        val results = analyzeBefore(data, width, height, rect)
        return DataAnalyzerResult(results, rect)
    }

    private fun analyzeBefore(data: ByteArray?, dataWidth: Int, dataHeight: Int, rect: Rect): Array<Result>? {
        return if (processDispatch != null) {
            analyze(processDispatch!!.dispatch(data, dataWidth, dataHeight, rect), dataWidth, dataHeight, rect.left, rect.top, rect.width(), rect.height())
        } else {
            analyze(data, dataWidth, dataHeight, rect.left, rect.top, rect.width(), rect.height())
        }
    }

    abstract fun analyze(data: ByteArray?, dataWidth: Int, dataHeight: Int, left: Int, top: Int, width: Int, height: Int): Array<Result>?
}
